package com.shell.guard.config;

import java.io.UnsupportedEncodingException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.shell.bee.base.utils.Encryptor;

@Configuration
@EnableConfigurationProperties({ DataSourceProperties.class })
public class DatasourceConfig {

	@Autowired
	private DataSourceProperties dataSourceProperties;
	
	private DruidDataSource pool;

	@Bean
	public DataSource dataSource() {
		String userName = null;
		String password = null;
		try {
			userName = Encryptor.decrypt(this.dataSourceProperties.getUsername());
			password = Encryptor.decrypt(this.dataSourceProperties.getPassword());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.pool = new DruidDataSource();
		this.pool.setDriverClassName(this.dataSourceProperties.getDriverClassName());
		this.pool.setUrl(this.dataSourceProperties.getUrl());
		this.pool.setUsername(userName);
		this.pool.setPassword(password);

		this.pool.setTimeBetweenEvictionRunsMillis(this.dataSourceProperties.getTimeBetweenEvictionRunsMillis());

		this.pool.setMaxWait(this.dataSourceProperties.getMaxWait());

		this.pool.setMinIdle(this.dataSourceProperties.getMinIdle());

		this.pool.setMaxActive(this.dataSourceProperties.getMaxActive());

		this.pool.setInitialSize(this.dataSourceProperties.getInitialSize());

		return this.pool;
	}
}